package com.hispeed.management.service.impl;

import com.hispeed.management.service.IRedisService;
import com.hispeed.management.util.JsonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * Redis Service实现
 *
 * @author zhangzb
 * @create 2017-06-19 13:40
 **/
@Service
public class RedisServiceImpl implements IRedisService {

    @Autowired
    private RedisTemplate<String, ?> redisTemplate;

    /**
     * 设置给定key的值，若key已经存在，set复写旧值
     * @param key
     * @param value
     * @return
     */
    @Override
    public boolean set(final String key, final String value) {
        boolean result = redisTemplate.execute(new RedisCallback<Boolean>() {
            public Boolean doInRedis(RedisConnection connection) throws DataAccessException {
                RedisSerializer<String> serializer = redisTemplate.getStringSerializer();
                connection.set(serializer.serialize(key), serializer.serialize(value));
                return true;
            }
        });
        return result;
    }

    /**
     * 设置给定key的值和有效时间，若key已经存在，复写旧值，并重新计算有效时间
     * @param key
     * @param value
     * @param expire
     * @return
     */
    @Override
    public boolean set(final String key, final String value, final long expire) {
        boolean result = redisTemplate.execute(new RedisCallback<Boolean>() {
            public Boolean doInRedis(RedisConnection connection) throws DataAccessException {
                RedisSerializer<String> serializer = redisTemplate.getStringSerializer();
                connection.setEx(serializer.serialize(key), expire, serializer.serialize(value));
                return true;
            }
        });
        return result;
    }


    /**
     * 获取key的value
     * @param key
     * @return
     */
    @Override
    public String get(final String key){
        String result = redisTemplate.execute(new RedisCallback<String>() {
            public String doInRedis(RedisConnection connection) throws DataAccessException {
                RedisSerializer<String> serializer = redisTemplate.getStringSerializer();
                byte[] value =  connection.get(serializer.serialize(key));
                return serializer.deserialize(value);
            }
        });
        return result;
    }

    /**
     * 设置给定key的过期时间（单位为秒）
     * @param key
     * @param expire
     * @return
     */
    @Override
    public boolean expire(final String key, final long expire) {
        return redisTemplate.expire(key, expire, TimeUnit.SECONDS);
    }

    /**
     * 判断给定的key是否存在
     * @param key
     * @return
     */
    @Override
    public boolean exist(final String key) {
        if (key!=null&&!("").equals(key)){
            boolean result = redisTemplate.execute(new RedisCallback<Boolean>() {

                public Boolean doInRedis(RedisConnection connection) throws DataAccessException {
                    RedisSerializer<String> serializer = redisTemplate.getStringSerializer();
                    boolean flag = connection.exists(serializer.serialize(key));
                    return flag;
                }
            });
            return result;
        }
        return false;
    }

    /**
     * 存放object类型，若key已经存在，set复写旧值
     * @param key
     * @param object
     * @throws IOException
     */
    @Override
    public void setObject(String key, Object object) throws IOException {
        final String value = JsonUtil.toJson(object);
        set(key, value);
    }

    /**
     * 存放object类型，若key已经存在，复写旧值，并重新计算有效时间
     * @param key 键
     * @param object object类型
     * @param expire 超时时间
     * @throws IOException
     */
    @Override
    public void setObject(String key, Object object, long expire) throws IOException {
        setObject(key,object);
        expire(key,expire);
    }

    /**
     * 将一个或多个值插入到列表头部
     * @param key
     * @param obj
     * @return
     * @throws IOException
     */
    public long lpush(final String key, Object obj) throws IOException {
        final String value = JsonUtil.toJson(obj);
        long result = redisTemplate.execute(new RedisCallback<Long>() {
            @Override
            public Long doInRedis(RedisConnection connection) throws DataAccessException {
                RedisSerializer<String> serializer = redisTemplate.getStringSerializer();
                long count = connection.lPush(serializer.serialize(key), serializer.serialize(value));
                return count;
            }
        });
        return result;
    }

    /**
     * 将一个或多个值插入到列表尾部
     * @param key
     * @param obj
     * @return
     * @throws IOException
     */
    public long rpush(final String key, Object obj) throws IOException {
        final String value = JsonUtil.toJson(obj);
        long result = redisTemplate.execute(new RedisCallback<Long>() {
            @Override
            public Long doInRedis(RedisConnection connection) throws DataAccessException {
                RedisSerializer<String> serializer = redisTemplate.getStringSerializer();
                long count = connection.rPush(serializer.serialize(key), serializer.serialize(value));
                return count;
            }
        });
        return result;
    }

    /**
     * 从 list 的头部删除元素，并返回删除元素
     * @param key
     * @return
     */
    @Override
    public String lpop(final String key) {
        String result = redisTemplate.execute(new RedisCallback<String>() {
            public String doInRedis(RedisConnection connection) throws DataAccessException {
                RedisSerializer<String> serializer = redisTemplate.getStringSerializer();
                byte[] res =  connection.lPop(serializer.serialize(key));
                return serializer.deserialize(res);
            }
        });
        return result;
    }

    /**
     * 从 list 的尾部删除元素，并返回删除元素
     * @param key
     * @return
     */
    @Override
    public String rpop(final String key) {
        String result = redisTemplate.execute(new RedisCallback<String>() {
            @Override
            public String doInRedis(RedisConnection connection) throws DataAccessException {
                RedisSerializer<String> serializer = redisTemplate.getStringSerializer();
                byte[] res =  connection.rPop(serializer.serialize(key));
                return serializer.deserialize(res);
            }
        });
        return result;
    }

}
